package com.westa.smallshop.login;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.westa.smallshop.data.source.AccountDataSource;
import com.westa.smallshop.data.source.remote.BaseDataSource;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by cy123 on 2016/9/13.
 */
public class LoginPresenter implements LoginContract.Presenter {


    @NonNull
    private final LoginContract.View mLoginView;

    @NonNull
    private final AccountDataSource mAccountDataSource;

    public LoginPresenter(@NonNull LoginContract.View loginView, @NonNull AccountDataSource accountDataSource) {

        mLoginView = checkNotNull(loginView);
        mAccountDataSource = checkNotNull(accountDataSource);

        mLoginView.setPresenter(this);
    }

    @Override
    public void doLogin(final String account, String password) {
        if (TextUtils.isEmpty(account)) {

            mLoginView.showAccountEmptyError();
            return;
        }

        if (TextUtils.isEmpty(password)) {

            mLoginView.showPasswordEmptyError();
            return;
        }

        mLoginView.showLoginDialogProgress();
        mAccountDataSource.login(account, password, new BaseDataSource.LoadCallBack<JSONObject>() {
            @Override
            public void onLoadDataSuccessful(JSONObject data) {
                if (mLoginView.isActive()) {
                    if (TextUtils.equals(data.getString("result"), "0")) {
                        mLoginView.dismissDialogProgress();
                        mLoginView.loginSuccessful();
                    } else {
                        mLoginView.loginFailed("登录失败");
                        mLoginView.dismissDialogProgress();
                    }
                }
            }

            @Override
            public void onLoadDataFailed() {
                mLoginView.loginFailed("登录失败");
                mLoginView.dismissDialogProgress();
            }
        });
    }

    @Override
    public void cancelLogin() {

        mAccountDataSource.cancelLoadRequest();
    }

    @Override
    public void start() {

    }


    @Override
    public void destroy() {

        mAccountDataSource.cancelLoadRequest();
    }
}
